﻿module Sustainalytics.Portfolio {
    import Common = Sustainalytics.Common;

    // Portfolio List controller
    export class SubscribeToPortfolioController {
        
        public subscribeList: SubscribeToPortfolioDto[];
        private accountId: string;
        private userId: string;
        public hasEditPermission: boolean;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private SubscribeToPortfolioService: SubscribeToPortfolioService,
            private notificationFactory: Common.INotificationFactory,
            private ControversyAlertPermissionsService: ControversyAlert.Security.IControversyAlertPermissionsService,
            private $modal: Common.IModal) {

            var ctx = this;

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }

            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;
            
            ctx.hasEditPermission = ctx.ControversyAlertPermissionsService.hasControversyAlert();
            $scope['subscribeToPortfolio'] = ctx;

            ctx.getSubscriptions();
        }

        public getSubscriptions() {
            var ctx = this;
            var promise = ctx.SubscribeToPortfolioService.getAllSubscriptionForUser(ctx.userId, ctx.accountId);
            promise.then(data => {
                ctx.subscribeList = data['subscriptionListDto'];
                ctx.subscribeList.forEach(s=>
                {
                    s.portfolioList.filter(p=> {
                        if (p.portfolioId == "00000000-0000-0000-0000-000000000000")
                        {
                            p.portfolioName = AddEditSubscriptionController.allCompaniesLabel;
                        }});
                });
            });

            return promise;
        }

        public addAlert() {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: '/Views/Portfolio/addEditSubscription.tpl.html',
                    controller: 'AddEditSubscriptionController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        item: function () {
                            return null;
                        }
                    }
                });

            modalInstance.result.then((out) => {
                ctx.getSubscriptions();
            });
        }

        public editAlert(currentItem: SubscribeToPortfolioDto) {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: '/Views/Portfolio/addEditSubscription.tpl.html',
                    controller: 'AddEditSubscriptionController',
                    size: 'lg',
                    backdrop: false,
                    resolve: {
                        item: function () {
                            var itemToSend = new SubscribeToPortfolio();
                            itemToSend.accountId = currentItem.accountId;
                            itemToSend.userId = currentItem.userId;
                            itemToSend.enabled = currentItem.enabled;
                            itemToSend.frequency = currentItem.frequency;
                            itemToSend.id = currentItem.id;
                            var portIds = new Array();
                            currentItem.portfolioList.forEach(port => {
                                portIds.push(port.portfolioId);
                            });
                            itemToSend.portfolioIds = portIds;
                            return itemToSend;
                        }
                    }
                });

            modalInstance.result.then((out) => {
                ctx.getSubscriptions();
            });
        }

        public enableAlert(currentItem: SubscribeToPortfolioDto) {
            var ctx = this;

            var modalInstanceSubscribe = ctx.$modal.open({
                templateUrl: 'Views/Portfolio/portfolioExists_dialog.tpl.html',
                controller: 'PortfolioCheckController',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    message: function () {
                        return "Are you sure you want to enable the alert?";
                    },
                    informationMessage: function () {
                        var hasSharedPortfolio = false;
                        for (var i = 0; i < currentItem.portfolioList.length; i++)
                            if (!currentItem.portfolioList[i].isMyPortfolio)
                                hasSharedPortfolio = true;
                        if (hasSharedPortfolio)
                            return "Companies in portfolios that you did not create, will be removed from the email alert when the owner deletes or stops sharing the item."
                    }
                }
            });

            modalInstanceSubscribe.result.then((out) => {
                if (out['portfolioCheck'] == true) {
                    var promise = ctx.SubscribeToPortfolioService.updateStatusSubscription(currentItem.id, ctx.userId, ctx.accountId, true);
                    promise.then(data => {
                        ctx.getSubscriptions();
                    });
                } 
            });
        }

        public disableAlert(currentItem: SubscribeToPortfolioDto) {
            var ctx = this;

            var modalInstanceSubscribe = ctx.$modal.open({
                templateUrl: 'Views/Portfolio/portfolioExists_dialog.tpl.html',
                controller: 'PortfolioCheckController',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    message: function () {
                        return "Are you sure you want to disable the alert?";
                    },
                    informationMessage: function () {
                    }
                }
            });

            modalInstanceSubscribe.result.then((out) => {
                if (out['portfolioCheck'] == true) {
                    var promise = ctx.SubscribeToPortfolioService.updateStatusSubscription(currentItem.id, ctx.userId, ctx.accountId, false);
                    promise.then(data => {
                        ctx.getSubscriptions();
                    });
                }
            });
        }

        public deleteAlert(id: string) {
            var ctx = this;
            var promise = ctx.SubscribeToPortfolioService.deleteSubscription(id, ctx.userId, ctx.accountId);
            promise.then(data => {
                ctx.getSubscriptions();
            });

            return promise;
        }

        //#region Tutotial
        public openVideoPopup() {
            var ctx = this;

            var $modalInstance = ctx.$modal.open(
                {
                    templateUrl: '../../../Views/tutorial_dialog.tpl.html',
                    controller: 'TutorialController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        title: function () {
                            return "Portfolio Management and Monitoring";
                        },
                        url: function () {
                            return "http://www.sustainalytics.com/sites/default/files/uploads/2015-08-25-GAV3-PortfolioManagement.mp4";
                        }

                    }

                });
        }
        //#endregion
    }

    // register controller with Portfolio Angular module
    angular.module(portfolioModuleName).controller('SubscribeToPortfolioController',
        ['$rootScope', '$scope', '$q', 'SubscribeToPortfolioService', 'notificationFactory', 'ControversyAlertPermissionsService', '$modal', SubscribeToPortfolioController]);
} 
